from lib2to3.fixes.fix_input import context

from django.shortcuts import render
from django.views.generic import TemplateView

from commodity.models import Types, CommodityInfos



# Create your views here.
def indexView(request):
    """
    处理首页请求
    """
    title = "首页"#页面标题
    #当前页面为首页时，首页的class=‘active’

    classContent = ""#用于页面样式控制的的变量
    #获取销量最高的8个商品，按照向量降序排序
    commodityInfos = CommodityInfos.objects.order_by("-sold").all()[:8]
    #获取所有的商品分类
    types = Types.object.all()
    #筛选儿童服饰分类下的二级分类，以列表形式返回
    c1 = [x.seconds for x in types if x.firsts == "儿童服饰"]
    #获取销量最高的5个商品
    clothes = CommodityInfos.objects.filter(types__in=c1).order_by("-sold")[:5]
    #筛选奶粉辅食的二级分类
    f1 = [x.seconds for x in types if x.firsts == "奶粉辅食"]
    #获取销量最高的5个商品
    food = CommodityInfos.objects.filter(types__in=f1).order_by("-sold")[:5]

    g1 = [x.seconds for x in types if x.firsts == "儿童用品"]
    # 获取销量最高的5个商品
    goods = CommodityInfos.objects.filter(types__in=g1).order_by("-sold")[:5]

    return render(request,"index.html",locals())

#基于类的视图，处理首页请求
class indexClassView(TemplateView):
    #指定渲染的模板
    template_name = "index.html"
    #可选，指定模板引擎
    template_engine = None
    #指定响应的Content-type
    extra_context = {"title":"首页","classContent": ""}

    def get_context_data(self, **kwargs):

        context = super(indexClassView,self).get_context_data(**kwargs)

        context["commodityInfos"] = CommodityInfos.objects.order_by("-sold").all()[:8]

        types = Types.objects.all()

        cl =[x.seconds for x in types if x.firsts =="儿童服饰"]
        context["cloths"] = CommodityInfos.objects.filter(types__in=cl).order_by("-sold")[:5]
        fl = [x.seconds for x in types if x.firsts == "奶粉辅食"]
        context["food"] = CommodityInfos.objects.filter(types__in=fl).order_by("-sold")[:5]
        gl = [x.seconds for x in types if x.firsts == "儿童用品"]
        context["goods"] = CommodityInfos.objects.filter(types__in=gl).order_by("-sold")[:5]
        return context


    def get(self, request, *args, **kwargs):
        """
        处理HTTP POST请求

        """
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)


def page_not_found(request,exception):
    return render(request, '404.html', status=404)


def page_error(request):
    return render(request, '404.html', status=500)